#include "ET++.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "ListSelectorDialog.h"

#include "Class.h"
#include "TextItem.h"
#include "Scroller.h"
#include "Buttons.h"
#include "System.h"
#include "OrdColl.h"
#include "ObjGridView.h"

enum FileDialogParts {
	eFDTopPart,
	eFDListPart,
	eFDEditTitlePart,
	eFDEditPart,
	eFDActionPart
};

const int
	cIdList   = cIdFirstUser + 111,
	cIdUpdate = cIdFirstUser + 112;

//---- ListSelectorDialog ------------------------------------------------------
		
NewMetaImpl(ListSelectorDialog,Dialog, (TP(list), TP(listView), TP(scroller)));

ListSelectorDialog::ListSelectorDialog(const char *nm) : Dialog(nm)
{
}

ListSelectorDialog::~ListSelectorDialog()
{
	if (listView) {
		listView->SetCollection(0, FALSE);
		SafeDelete(listView);
	}
}

Object *ListSelectorDialog::SelectObject(SeqCollection *l)
{
	list= l;

	Port *old= GrGetPort();
	int rc= ShowUnderMouse();
	if (old)
		GrSetPort(old);

	if (rc != cIdOk)
		return 0;
	Rectangle r(listView->GetSelection().BBox());
	if (r.IsNotEmpty())
		return list->At(r.origin.y);
	return 0;
}

VObject *ListSelectorDialog::DoMakeControls()
{
	return MakePart(eFDListPart);
}

VObject *ListSelectorDialog::DoMakeActions()
{
	return MakePart(eFDActionPart);
}

VObject *ListSelectorDialog::MakePart(int which)
{
	switch (which) {

	case eFDTopPart:
		return 0;

	case eFDListPart:
		listView= new ObjGridView(cIdList, this, 150);
		return scroller= new Scroller(listView, Point(150, cAutoSize));
		
	case eFDActionPart:
		return new HBox(20, (VObjAlign)(eVObjVBase|eVObjHEqual|eVObjHExpand),
			new ActionButton(cIdOk,     "Select", TRUE),
			new ActionButton(cIdCancel, "Cancel"),
			new ActionButton(cIdUpdate, "Update"),
			new ActionButton(cHELP,     "Help"),
			0
		);

	default:
		break;
	}
	return 0;
}

void ListSelectorDialog::DoSetDefaults()
{
	listView->SetCollection(list, FALSE);
	listView->SetSelection(Rectangle(gPoint0, gPoint1));
}

void ListSelectorDialog::InputKbd(Token &t)
{
	if (t.IsAscii() && scroller->ContainsPoint(t.Pos)) {
		if (t.Code != '\r' && t.Code != '\n')
			scroller->Input(t.Pos, t, GetWindow());
	} else
		Dialog::InputKbd(t);
}

void ListSelectorDialog::DoSetup()
{
	EnableItem(cIdOk, !listView->GetSelection().BBox().IsEmpty());
}

void ListSelectorDialog::Control(int id, int p, void *v)
{
	switch (id) {
	case cIdUpdate:
		DoSetDefaults();
		return;
	case cIdList:
		if (p == cPartCollDoubleSelect) {
			Dialog::Control(cIdOk, cPartAction, v);
			return;
		}
		break;
	default:
		break;
	}
	Dialog::Control(id, p, v);
}

Object *ListSelectorDialog::Select(SeqCollection *l, const char *nm)
{
	ListSelectorDialog *dia= new ListSelectorDialog(nm);
	Object *op= dia->SelectObject(l);
	gSystem->AddCleanupObject(dia);
	return op;
}

